package com.srb.sms.controller.api;

import com.srb.common.exception.Assert;
import com.srb.common.result.R;
import com.srb.common.result.ResponseEnum;
import com.srb.common.util.RandomUtils;
import com.srb.sms.feign.ICoreUserInfoFeignClient;
import com.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信管理")
@Slf4j
//@CrossOrigin
@RestController
@RequestMapping(value = {"/api/sms"})
public class ApiSmsController {

    @Autowired
    private SmsService service;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ICoreUserInfoFeignClient userInfoFeignClient;

    @ApiOperation(value = "获取验证码")
    @GetMapping(value = {"/send/{mobile}"})
    public R send(
            @ApiParam(value = "手机号",required = true)
            @PathVariable(value = "mobile") String mobile){
        //校验手机号是否为空
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //校验手机号是否合法
//        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

        //判断手机号是否已经注册
        boolean flag = userInfoFeignClient.checkMobile(mobile);
        Assert.isTrue(flag == false,ResponseEnum.MOBILE_EXIST_ERROR);

        Map<String, Object> map = new HashMap<>(1);
        String code = RandomUtils.getSixBitRandom();
        map.put("code", code);
//        service.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        redisTemplate.opsForValue().set("srb:sms:code:"+mobile,code,5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}
